//
//  KoiCategorySync.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 19.04.25.
//

import Foundation
class KoiCategorySync : KoiDataSyncBase<AccountingCategory> {
    
    private let categoryDao = KoiAccountingDB.standard.getCategoryDao()
    
    override var syncPref: String {
        return "sync:category:"
    }
    
    override func getPullResponse(offset: Int? = nil) -> Result<KoiSyncResponseData<AccountingCategory>?, KoiNetError> {
        var params = ["last_sv": 0]
        if let offset = offset {
            params["offset"] = offset
        }
        return KoiNetBase.baseShared.requestAuth(
            path: "category/sync/pull",
            method: .post,
            parameters: params
        )
    }
    
    override func getPushResponse(list: Array<AccountingCategory>, offset: Int) -> Result<KoiSyncResponseData<AccountingCategory>?, KoiNetError> {
        var params = [String: Any]()
        params["list"] = list.jsonEncode()
        params["offset"] = offset
        
        return KoiNetBase.baseShared.requestAuth(
            path: "category/sync/push",
            method: .post,
            parameters: params
        )
    }
    
    override func getPushData(pageSize: Int, offset: Int) -> Array<AccountingCategory> {
        return categoryDao.getPushData(pageSize: pageSize, offset: offset, uid: uid, bookId: bookId)
    }
    
    override func updatePullData(list: Array<AccountingCategory>, lastSv: Int) throws {
        // 拉回来的数据，默认值是 not sync ，需要手动设置为 synced
        var list = list
        for i in list.indices {
            list[i].dataFlag = DataFlag.synced.rawValue
            list[i].sv = lastSv
        }
        try categoryDao.updateSync(list: list)
    }
    
    override func updatePushData(list: Array<AccountingCategory>?, lastSv: Int) throws {
        guard var list = list else { return }
        for i in list.indices {
            list[i].dataFlag = DataFlag.synced.rawValue
            list[i].sv = lastSv
        }
        try categoryDao.updateSync(list: list)
    }
}
